<template>
  <!-- 弹窗 -->
  <el-dialog :title="formData.id?'编辑员工':'新增员工'" :visible="showDialog" @close="closeFn">
    <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" />
      </el-form-item>
      <el-form-item label="头像">
        <ImageUpload ref="employPhoto" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-row type="flex" justify="end">
        <el-button type="primary" @click="connfirmFn">确认</el-button>
        <el-button @click="closeFn">取消</el-button>
      </el-row>
    </span>
  </el-dialog>
</template>

<script>
import { register } from '@/api/user'
import { getEmployeeById, updateEmployee } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        username: '',
        email: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          {}
        ],
        email: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ]
      },
      myImg:{}
    }
  },
  methods: {
    image(){
      this.formData = this.myImg
      this.$refs.employPhoto.fileList = []
      this.$refs.employPhoto.fileList.push({
        url:this.myImg.image
      })
    },
    // 根据id获取数据
    async getEmployeeById(id) {
      const res = await getEmployeeById(id)
      this.formData = res.data
      this.myImg = res.data
      console.log(61, res.data)
      this.$nextTick(()=>{
        this.image()
      })
    },
    // 确认 / 新增
    connfirmFn() {
      const upload = this.$refs.employPhoto
      this.formData.image = upload.fileList[0] && upload.fileList[0].url
      // 校验表单
      this.$refs.form.validate().then(async() => {
        if (this.formData.id) {
          // 编辑
          // 调用接口 编辑
          await updateEmployee(this.formData)
        } else {
          // 新增
          // 调用接口 新建注册
          await register(this.formData)
        }
        // 关闭弹窗 清空表单
        this.closeFn()
        // 更新列表
        this.$emit('getEmploy')
      })
    },
    closeFn() {
      // 子传父 关闭弹窗
      this.$emit('update:showDialog')
      // 清空校验
      this.$refs.form.resetFields()
      // 清空表单
      this.formData = {
        username: '',
        email: '',
        password: ''
      }
    }
  }
}
</script>

<style>

</style>
